<?php

/**
 * 强制结单
 */
class indftController extends baseController {
	
	public function __construct(){
		if(!UserPrivHelper::check('indent-force')){
			die("无权操作");
		}
	}
	
	public function show(){
		$indent_id = fetch_a_int('id');
		if(!($indent=$this->getIndent($indent_id, $errmsg))){
			Show::warn($errmsg);
		}
		
		switch(fetch_a_int('type')){
			case 2: return $this->changeSupplier($indent);
			case 1: return $this->forceTerm($indent);
		}
		
		/*
		 * 检查 未质量的入库单
		 */
		if(Db::get('Bound')->count()->where(array(
			'type'	=> Bound::TYPE_CK,
			'indent_id' => $indent_id,
			'effect'	=> 0,
		))->getCol()){
			$this->assign('unclosure', 1);
		}
		
		$this->assign('indent', $indent);
		$this->display();
	}
	
	/**
	 * 更改供应商
	 */
	public function changeSupplier($indent){
		$newitems = array();
		
		if($indent['back_flow']){ //有入库
			foreach($indent['items'] as $ware_id=>$item){
				$this->diffFunc($item, null);
				if($item['amount_diff'] > 0){
					$newitems[$item['ware_id']] = $item;
				}
			}
		}
		else{ //无入库
			$newitems = $indent['items'];
			array_walk($newitems, array($this, 'diffFunc'));
		}
		
		/*
		 * 若用户选择了供应商，则显示选中的供应商的报价；否则从供应商列表取前三个显示报价；
		 */
		$where	= '1';
		$limit	= 3;
		if($sspids=fetch_a_array('sspid')){
			$sspids	= array_map("intval", $sspids);
			$limit	= count($sspids);
			$where	.= sprintf(' AND id IN (%s)', join(',', $sspids));
		}
		else{
			$where .= " AND id!={$indent['supplier_id']}";
		}
		$suppliers = Supplier::getList($where, 0, $limit);
		$sspids = array_keys($suppliers);
		$this->assign('suppliers', $suppliers);
		$this->assign('sspids', $sspids); //已选供应商ID
		/*
		 * 取报价
		 */
                
                $ware_id = ($newitems)?array('ware_id','IN',array_keys($newitems)):'';
                
		$costs	= Db::get('SupplierQuote')->select()->where(
						array('supplier_id','IN',$sspids), 
						$ware_id)
				->getAll();
		foreach($costs as $c) {
			$newitems[$c['ware_id']]['suppliers'][$c['supplier_id']] = $c;
		}
		
		$this->assign('indent', $indent);
		$this->assign('itemsdiff', $newitems);
		$this->assign('all_suppliers',	Supplier::getList());
		$this->display('indft-chgsup');
	}
	
	/**
	 * 保存更改供应商
	 */
	public function dochgsup(){
		$indent_id = fetch_a_int('id');
		if(!($indent=$this->getIndent($indent_id, $errmsg))){
			Show::warn($errmsg);
		}
		Db::get()->trans()->on();
		
		$supplier_id = fetch_a_int('supplier_id');
		$supplier = Supplier::get($supplier_id);
		if(!$supplier){
			$this->twarn('无此供应商');
		}
		
		if($indent['back_flow']==1){
			/*
			 * todo:
			 * 新订单的制作人及部门与原订单相同
			 * 新订单是否需要再审批？ 不审
			 * 
			 * indent_items.off=1
			 * indent.back_flow=2
			 * indent.total=renew()
			 * 
			 * copy indent&indent_items to new
			 * 
			 */
			if(!isset($_POST['itemoff']) || !isset($_POST['amount'])){
				$this->twarn('参数错误');
			}
			/*
			 * 计算原订单总价，关闭原订单
			 * 原订单材料，数量计为回库数量，删除未入库材料
			 */
			$total = 0.0;
			foreach($_POST['itemoff'] as $itemid=>$amount){
				if(!isset($indent['items'][$itemid])){
					$this->twarn('材料不存在');
				}
				$r = Db::get('IndentItems')->update(array('off'=>1,'amount'=>$amount))
						->where(array('indent_id'=>$indent_id,'ware_id'=>$itemid))->exec();
				if( !$r || !Db::get('IndentItems')->affectedRows()) {
					$this->twarn('关闭原订单材料出错');
				}
				$total += ($amount * $indent['items'][$itemid]['price']);
			}
			if(!Indent::update($indent_id, array('total'=>$total,'back_flow'=>2))){
				$this->twarn('关闭原订单出错');
			}
			/*
			 * 删除多余的材料记录
			 */
			$r = Db::get('IndentItems')->delete()->where(
						array('indent_id'=>$indent_id),
						array('ware_id','NOT IN',array_keys($_POST['itemoff']))
					)->exec();
			if(!$r){
				$this->twarn('清除多余材料失败');
			}
			
			/*
			 * 复制到新订单
			 */
			$total = 0.0;
			$items = array();
			//准备IndentItems，计算total
			foreach($_POST['amount'] as $itemid=>$amount){
				if(!isset($indent['items'][$itemid])){
					$this->twarn('材料不存在');
				}
				
				if(!($price = SupplierQuote::getQuote($supplier_id, $itemid))){
					$this->twarn('材料无报价：'. $indent['items'][$itemid]['name']);
				}
				
				$items[$itemid] = array_merge($indent['items'][$itemid], array(
					'indent_id'	=> 0,
					'price'		=> $price,
					'amount'	=> $amount,
					'amount_back'	=> 0,
					'off'		=> 0,
				));
				
				$total += ( $price * $amount );
			}
			//生成新订单
			$indent_id = Indent::add(array_merge($indent, array(
				'id'			=> 0,
				'supplier_id'	=> $supplier['id'],
				'supplier'		=> $supplier['full_name'],
				'addtime'		=> time(),
				'sum_month'		=> date('Ym'),
				'sno'			=> Sno::cgen('indent'),
				'remark'		=> fetch_a_string('remark'),
				'total'			=> $total,
				'back_flow'		=> 0,
				'audit_flow'	=> 0,
				'pr_no'			=> fetch_a_string('pr_no'),
			)));
			if(!$indent_id){
				$this->twarn('增加新订单失败');
			}
			foreach($items as $itemid => $item){
				$item['indent_id']	= $indent_id;
				if(!IndentItems::add($item)){
					$this->twarn('增加新订单材料失败：'. $item['name']);
				}
			}
			
			//增加订单审批
			if(!ReviewerHelper::expand(Reviewer::CLS_INDENT, $indent_id, $indent['dept_id'])){
				$this->twarn(ReviewerHelper::getLastError());
			}
			
		}
		else{ // 直接修改原订单
			
			/*
			 * todo:
			 * 
			 * indent_items.price
			 * indent.total=renew()
			 * indent.supplier_id,supplier
			 * indent.total
			 * 
			 */
			$total = 0.0;
			foreach($_POST['amount'] as $itemid=>$amount){
				if(!isset($indent['items'][$itemid])){
					$this->twarn('材料不存在');
				}
				
				if(!($price = SupplierQuote::getQuote($supplier_id, $itemid))){
					$this->twarn('材料无报价：'. $indent['items'][$itemid]['name']);
				}
				
				if( !Db::get('IndentItems')->update(array('price'=>$price))->where(array('indent_id'=>$indent_id,'ware_id'=>$itemid))->exec()
						|| !Db::get('IndentItems')->affectedRows()) {
					$this->twarn('修改订单材料价格失败');
				}
				$total += $amount*$price;
			}
			if(!Indent::update($indent_id, array('total'=>$total,'supplier_id'=>$supplier_id,'supplier'=>$supplier['full_name']))){
				$this->twarn('修改订单失败');
			}
			
		}
		
		Db::get()->trans()->commit();
		Show::note('操作成功', url("indent-view/id/{$indent_id}"));
		
	}
	
	/**
	 * 强制关闭订单
	 */
	public function forceTerm($indent){
		$this->assign('indent', $indent);
		$this->display('indft-frcterm');
	}

	public function dofrcterm(){
		$indent_id = fetch_a_int('id');
		if(!($indent=$this->getIndent($indent_id, $errmsg))){
			Show::warn($errmsg);
		}

		$feedbacks = fetch_a_array('feedback');
		//订单源自需求IDs
		$dmids = Db::get('Demand')->select('id')->where(array('summary_id'=>$indent['summary_id']))->getCols();

		Db::get()->trans()->on();
		/*
		 * 关闭订单材料，设置demand_items回馈状态
		 */
		$total = 0.0;
		foreach($indent['items'] as $itemid=>$item){
			//终止订单，应该修改订单总价
			$total += $item['price'] * $item['amount_back'];
			if($item['off']){ continue; }
			
			$r = Db::get('IndentItems')->update(array('off'=>1))
					->where(array('indent_id'=>$indent_id,'ware_id'=>$item['ware_id']))->exec();
			if(!$r || !Db::get()->affectedRows()){
				$this->twarn("关闭订单材料出错");
			}

			//demand_items.state/feedback
			$r = Db::get('DemandItems')->update(array(
					'state' => DemandItems::STATE_FAIL,
					'feedback' => fetch_a_string($itemid,$feedbacks)
				))->where(array('demand_id','IN',$dmids),array('ware_id'=>$itemid))->exec();
			if(!$r || !Db::get()->affectedRows()){
				$this->twarn("修改需求回馈状态失败");
			}
		}

		$r = Indent::update($indent_id, array('total'=>$total,'back_flow'=>2));
		if(!$r || !Db::get()->affectedRows()){
			$this->twarn("修改订单信息失败");
		}

		Db::get()->trans()->commit();
		Show::note('终止订单成功', url('indent-force'));
	}
	
	private function getIndent($indent_id, &$errmsg=''){
		$indent = Indent::get($indent_id);
		if(!$indent){
			$errmsg = '无此采购订单记录';
			return false;
		}
		if($indent['audit_flow']!=1){
			$errmsg = '采购订单未通过审核，不能做强制结单操作';
			return false;
		}
		if($indent['back_flow']==2){
			$errmsg = '采购订单已完成入库，不能做强制结单操作';
			return false;
		}
		$indent['items'] = IndentItems::getByIndent($indent_id);
		return $indent;
	}
	
	private function diffFunc(&$v, $k){
		$v['amount_diff'] = $v['amount'] - $v['amount_back'];
	}
	
	private function twarn($msg){
		Db::get()->trans()->rollback();
		Show::warn($msg);
	}
	
}

?>
